class User < ApplicationRecord
  attr_accessor :remember_token

  has_many :posts, dependent: :destroy
  validates :email, uniqueness: true
  validates :username,  presence: true, uniqueness: {  message: '登录用户名已经存在' }
  has_many :active_relationships, class_name: "Relationship",foreign_key: "comment_id", dependent: :destroy
  has_many :commenting, through: :active_relationships, source: :comment_id


  # 返回指定字符串的哈希摘要
  def User.digest(string)
    cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
        BCrypt::Engine.cost
    BCrypt::Password.create(string, cost: cost)
  end

  # 返回一个随机令牌
  def User.new_token
    SecureRandom.urlsafe_base64
  end

    # 忘记用户
    def forget
      update_attribute(:remember_digest, nil)
    end
    # 为了持久会话,在数据库中记住用户
    def remember
      self.remember_token = User.new_token
      update_attribute(:remember_digest, User.digest(remember_token))
    end

    # 如果指定的令牌和摘要匹配,返回 true
    def authenticated?(remember_token)
      if remember_digest.nil?
        return false
      end
      BCrypt::Password.new(remember_digest).is_password?(remember_token)
    end
end
